package top.hepingan.java.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.DeviceUsage;
import top.hepingan.java.entity.MemberOrder;
import top.hepingan.java.entity.emnu.PlanType;
import top.hepingan.java.mapper.DeviceUsageMapper;
import top.hepingan.java.mapper.MemberOrderMapper;
import top.hepingan.java.service.IDeviceUsageService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

import static top.hepingan.java.entity.emnu.PayStatus.PENDING;

/**
 * <p>
 * 设备使用表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-09-22
 */
@Service
public class DeviceUsageServiceImpl extends ServiceImpl<DeviceUsageMapper, DeviceUsage> implements IDeviceUsageService {

    @Override
    public int ismember(String deviceId) {
        //未注册的
        LambdaQueryWrapper<DeviceUsage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DeviceUsage::getDeviceId,deviceId);
        DeviceUsage deviceUsage = this.getOne(lambdaQueryWrapper);
        if (deviceUsage==null){
            deviceUsage = new DeviceUsage();
            deviceUsage.setDeviceId(deviceId);
            this.save(deviceUsage);
            return 3;
        }

        //会员
        if(isMemberValid(deviceUsage)>0)
        {
            return 999;
        }

        //注册
        if(deviceUsage.getUsageCount()>0)
        {
            //默认调用了一次
            deviceUsage.setUsageCount(deviceUsage.getUsageCount()-1);
            this.updateById(deviceUsage);
        }

        return deviceUsage.getUsageCount()-1;
    }


    /**
     * 判断会员是否有效
     * @param deviceUsage 设备使用对象
     * @return true=会员有效, false=已过期或未开通
     */
    public static int isMemberValid(DeviceUsage deviceUsage) {

        if (deviceUsage.getMemberEndTime() == null) {
            return 0;
        }
        if (!deviceUsage.getIsMember()){
            return 0;
        }
        LocalDateTime endTime = deviceUsage.getMemberEndTime();
        long endMillis = endTime.atZone(ZoneId.systemDefault())
                .toInstant()
                .toEpochMilli();

        if(endMillis > System.currentTimeMillis())
        {
            return 999;
        }


        return 0;
    }
    public static String generateOrderNo() {
        // 时间戳 yyyyMMddHHmmss
        String time = new java.text.SimpleDateFormat("yyyyMMddHHmmss")
                .format(new java.util.Date());
        // 6位随机数
        int random = (int) ((Math.random() * 9 + 1) * 100000);
        return time + random;
    }
    @Autowired
    private MemberOrderMapper memberOrderMapper;
    @Override

    public Result openMember(String deviceId, String planType) {
        // 订单号
        String ordeId =generateOrderNo();
        // 2. 校验参数
        if (deviceId == null || planType == null) {
            return Result.error("参数错误");
        }
        /// 枚举
        PlanType plan = PlanType.valueOf(planType);
        BigDecimal price;
        int durationDays;
        switch (plan) {
            case MONTHLY:
                price = new BigDecimal("10.1");
                durationDays=30;
                break;
            case QUARTERLY:
                price = new BigDecimal("30.1");
                durationDays=90;
                break;
            default:
                return Result.error("参数错误");
        }
        //创建订单号
        MemberOrder memberOrder = new MemberOrder();
        memberOrder.setRequestId(ordeId);
        memberOrder.setDeviceId(deviceId);
        memberOrder.setPlanType(planType);
        memberOrder.setAmount(price);
        memberOrder.setCreatedTime(LocalDateTime.now());
        memberOrder.setUpdatedTime(LocalDateTime.now());
        memberOrder.setStatus(PENDING.getDescription());
        memberOrderMapper.insert(memberOrder);
        //发送支付服务-监听消费-五分钟没有支付就取消支付
        return null;
    }

    @Override
    public Result selectoride(String deviceId) {
        LambdaQueryWrapper<MemberOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MemberOrder::getDeviceId,deviceId);
        List<MemberOrder> memberOrders = memberOrderMapper.selectList(lambdaQueryWrapper);
        return Result.ok().setData(memberOrders);
    }

}
